package com.example.jsonhelper

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.widget.*
import com.example.jsonhelper.framework.LyyBaseActivity
import com.google.gson.GsonBuilder
import com.google.gson.JsonParser
import org.json.JSONArray
import org.json.JSONObject

class ResultActivity : LyyBaseActivity() {
    private lateinit var tipLl:LinearLayout
    private lateinit var tipIv:ImageView
    private lateinit var tipTv:TextView
    private lateinit var sv:ScrollView
    private lateinit var resultTv:TextView
    private lateinit var copyBtn:Button
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_result)
        initViews()
        initTitleBar(title = "格式化结果", isShowBackIcon = true)
        initEvents()
    }

    private fun initViews() {
        tipLl=findViewById(R.id.tipLl)
        tipIv=findViewById(R.id.tipIv)
        tipTv=findViewById(R.id.tipTv)
        sv=findViewById(R.id.sv)
        resultTv=findViewById(R.id.resultTv)
        copyBtn=findViewById(R.id.copyBtn)
        val jsonStr = intent.getStringExtra(MainActivity.DATA_KEY)

        if (jsonStr!=null&&isJSONStr(jsonStr)){
            tipTv.text="老铁，这个JSON没毛病！"
            tipTv.setTextColor(Color.parseColor("#419F4B"))
            tipIv.setImageResource(R.drawable.icons8_checkmark_96px)
            val gson = GsonBuilder().setPrettyPrinting().serializeNulls().create()
            val resultText = gson.toJson(JsonParser.parseString(jsonStr))
            resultTv.setText(resultText)
            copyBtn.isEnabled=true
        }else{
            tipTv.text="老铁，这个JSON有点问题！"
            tipTv.setTextColor(Color.parseColor("#F64439"))
            tipIv.setImageResource(R.drawable.icons8_delete_sign_96px)
            resultTv.text=""
            copyBtn.isEnabled=false
        }

    }

    /**
     * 判断字符串是否为JSON字符串。既不是对象，也不是数组，那么它就不是JSON字符串，否则就是JSON字符串
     */
    private fun isJSONStr(str:String):Boolean{
        try {
            JSONObject(str)
        } catch (e: Exception) {
            try {
                JSONArray(str)
            } catch (e: Exception) {
                return false
            }
        }
        return true
    }

    private fun initEvents() {
        copyBtn.setOnClickListener {
            copyText(resultTv.text.toString())
        }
    }

    private fun copyText(content:String){
        val clipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        val text = ClipData.newPlainText("LABEL", content)
        clipboardManager.setPrimaryClip(text)
        Toast.makeText(this,"复制成功！",Toast.LENGTH_SHORT).show()
    }


}